package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.connect.DBconnect;
import com.toolbean.MyTools;

public class DoPost extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String driverClass = "com.mysql.jdbc.Driver";
		String user = "root";
        String pwd = "123456";
		String url = "jdbc:mysql://localhost:3306/shopdb?useUnicode=true&characterEncoding=utf-8";	
		Connection con=null;
		PreparedStatement pst = null;
		Statement st = null;
		ResultSet rs= null;
		HttpSession session=request.getSession();
		String path=request.getContextPath();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		MyTools mytools=new MyTools();
		RequestDispatcher rd=null;
		String adminname=null;
		adminname=mytools.toChinese(request.getParameter("adminname"));
	     String adminpassword=request.getParameter("adminpassword");
	     System.out.println(adminname);
		DBconnect dbcon = new DBconnect(driverClass,url,pwd,user);
		try {
			con = dbcon.getConnection();
			String sql = "select adminpassword from  admin where adminname=?";
		     pst = con.prepareStatement(sql);
			 pst.setString(1,adminname);
			 rs=pst.executeQuery();
			 String strpwd=null;
			 while(rs.next()){
				  strpwd=rs.getString("adminpassword");
			 }
			 if(strpwd!=null){
				 if(strpwd.equals(adminpassword)){
					 session.setAttribute("adminname",adminname);
					 session.setAttribute("adminpassword",adminpassword);
					 response.sendRedirect(path+"/admin/show.jsp");
				 }else{
					 request.setAttribute("a","1");
					 rd=request.getRequestDispatcher("HomePage.jsp");
					 rd.forward(request,response);
				 }
			 }else{
				 if(adminname!=null){
					 request.setAttribute("a","1");
					 rd=request.getRequestDispatcher("HomePage.jsp");
					 rd.forward(request,response);
				 }else if(adminname==""){
				 request.setAttribute("a","2");
				 rd=request.getRequestDispatcher("HomePage.jsp");
				 rd.forward(request,response);
				 }
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}
